import 'package:earclean/app/util/common_utils.dart';
import 'package:earclean/app/util/string_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class ChatController extends GetxController {
  //TODO: Implement ChatController

  final sendEnable = false.obs;
  final messages = [].obs;
  final title = ''.obs;
  final text = ''.obs;
  final textController = TextEditingController();
  Map userInfo = {};
  @override
  void onInit() {
    super.onInit();
  }

  checkInput() {
    bool a = isNotEmpty(text.value);
    if (a) {
      sendEnable.value = true;
    } else {
      sendEnable.value = false;
    }
  }

  @override
  void onReady() {
    // box.write("chatdata", []);
    getMessages();
    super.onReady();
  }

  getMessages() {
    // 获取数据

    messages.value = box.read('chatdata') ?? [];
    // messages.addAllIf(temp['info'] != null, temp['info'] ?? []);

    if (messages.isEmpty) {
      String time = DateTime.now().toString().split('.')[0];
      messages.insert(0, {"type": 2, "msg": "您好，请问有什么可以帮助您", 'time': time});
      box.write("chatdata", [
        {
          "type": 2,
          'time': time,
          'msg': '您好，请问有什么可以帮助您',
        }
      ]);
    }

    messages.refresh();
  }

  send() {
    String time = DateTime.now().toString().split('.')[0];
    // 获取数据
    List chatdata = box.read('chatdata') ?? [];

    chatdata.add({
      "type": 1,
      'time': time,
      'msg': text.value,
    });
    // 存储数据
    box.write("chatdata", chatdata);

    text.value = '';
    textController.text = '';
    checkInput();
    getMessages();

    // messages.addIf(text.value.length > 0, text.value);
  }

  @override
  void onClose() {}
}
